﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using Microsoft.Win32;

namespace Expect.Vs2008.Extensions
{
    [RunInstaller(true)]
    public partial class CustomInstaller : System.Configuration.Install.Installer
    {
        public CustomInstaller()
        {
            InitializeComponent();
        }

        [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            base.Install(stateSaver);
            InstalltemplatesForVS("Register", "9.0");
            InstalltemplatesForVS("Register", "10.0");
        }

        [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]
        public override void Uninstall(System.Collections.IDictionary savedState)
        {
            base.Uninstall(savedState);
            InstalltemplatesForVS("Unregister", "9.0");
            InstalltemplatesForVS("Unregister", "10.0");
        }

        private void InstalltemplatesForVS(string msg, string version)
        {
            try
            {
                var key = Registry.LocalMachine.OpenSubKey("SOFTWARE")
                    .OpenSubKey("Microsoft")
                    .OpenSubKey("VisualStudio")
                    .OpenSubKey(version)
                    .OpenSubKey("Setup")
                    .OpenSubKey("VS");

                if (key != null)
                {
                    string devenvpath = key.GetValue("EnvironmentPath").ToString();
                    this.Context.LogMessage(msg + " templates for Visual Studio " + version);
                    Process.Start(devenvpath, "/Setup").WaitForExit();
                }
            }
            catch (Exception)
            {
            }
        }        
    }
}
